//
// Created by Administrator on 2019/6/6 0006.
//

#include <cstdint>
#include <cstring>
#include "AudioChannel.h"
#include "faac.h"

RTMPPacket *AudioChannel::getAudioTag() {
    u_char *buf;
    u_long len;
    faacEncGetDecoderSpecificInfo(audioCodec, &buf, &len);
    int bodySize = 2 + len;
}

//不断调用
void AudioChannel::encodeData(int8_t *data) {
    int byteLen = faacEncEncode(audioCodec, reinterpret_cast<int32_t *>(data), inputSamples, buffer, maxOutputBytes);
    if (byteLen > 0) {
        RTMPPacket *packet = new RTMPPacket;
        int bodySize = 2 + byteLen;
        RTMPPacket_Alloc(packet, bodySize);
        packet->m_body[0] = 0XAF;
        if (mChannels == 1) {
            packet->m_body[0] = 0xAE;
        }
        packet->m_body[1] = 0x01;
        //编码之后aac数据内容， 不固定
        memcpy(&packet->m_body[2], buffer, byteLen);

        packet->m_hasAbsTimestamp = 0;
        packet->m_nBodySize = bodySize;
        packet->m_packetType = RTMP_PACKET_TYPE_AUDIO;
        packet->m_nChannel = 0x11;
        packet->m_headerType = RTMP_PACKET_SIZE_LARGE;
        audioCallback(packet);
    }
}

//初始化
void AudioChannel::setAudioEncInfo(int sampleInHz, int channels) {
    //最小缓冲大小
    audioCodec = faacEncOpen(sampleInHz, channels, &inputSamples, &maxOutputBytes);
    //设置参数
    faacEncConfigurationPtr config = faacEncGetCurrentConfiguration(audioCodec);
    config->mpegVersion = MPEG4;
    // lc标准
    config->aacObjectType = LOW;
    // 16为
    config->inputFormat = FAAC_INPUT_16BIT;
    //编码出原始数据 既不是adts也不是adif
    config->outputFormat = 0;
    faacEncSetConfiguration(audioCodec, config);
    buffer = new u_char[maxOutputBytes];
}

int AudioChannel::getInputSamples() {
    return inputSamples;
}

void AudioChannel::setAudioCallback(AudioChannel::AudioCallback audioCallback) {
    this->audioCallback = audioCallback;
}